package com.zs.grain.ui

import android.app.Application
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.zs.grain.*
import javax.inject.Inject
import com.zs.grain.service.*
import com.xnkj1688.semplibrary.mvvm.BaseViewModel
import com.xnkj1688.semplibrary.entity.*
//import com.zs.grain.service.MediaPlayerService
import com.zs.grain.tool.clockManage.LocalDataBase
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.concurrent.schedule

class DeployViewModel @Inject constructor(
    val mApp: Application,
    val mDataService: DataService,
    val mSignalRService: SignalRService,
    val mDeviceService:DeviceService,
    val mSoundService:SoundService
) : BaseViewModel(mApp) {
    //private var mpService: MediaPlayerService = MediaPlayerService()
    val enableScanQr = MutableLiveData<Boolean>()

    val name = MutableLiveData<String>()
    val uri = MutableLiveData<String>()
    val uriSeal = MutableLiveData<String>()
    val uriSugar = MutableLiveData<String>()
    val uriRemark = MutableLiveData<String>()
    val backgroundColor = MutableLiveData<Int>()
    val hasRemark = MutableLiveData<Boolean>()
    val price = MutableLiveData<String>()
    val btnSeal1 = MutableLiveData<Drawable>()
    val btnSeal2 = MutableLiveData<Drawable>()
    val btnSugar1 = MutableLiveData<Drawable>()
    val btnSugar2 = MutableLiveData<Drawable>()
    val btnSugar3 = MutableLiveData<Drawable>()
    val downCount = MutableLiveData<Int>()
    val proRemark = MutableLiveData<String>()
    var sugarIndex = 0;
    var sealIndex = 0
    var goodId:Long = 0
    private var mCheckTimer: Timer? = null
    var order: Order? = null
    var orderDetail: OrderDetail? = null
    var mReceipes: List<Receipe> = ArrayList<Receipe>()
    private val mResult = HashMap<Int, Int>()
    private lateinit var mMenu: Menu

    init {
        val payWays = mDataService.payWays
        enableScanQr.value = payWays.indexOf("alipay") >= 0
                || payWays.indexOf("weixin") >= 0
                || payWays.indexOf("lzf") >= 0
                || payWays.indexOf("icbc") >= 0
                || payWays.indexOf("chinaUms") >= 0


        this.startCheckDeployTimer()
        mDeviceService.isMakingProduct = true
        mSoundService.playSound2(2)
    }

    fun init(menuNo: Long) {
        this.order = null
        this.orderDetail = null
        var menu = mDataService.getMenu(menuNo)
        if (menu == null) return
        mMenu = menu
        goodId = mMenu.goodId
        var good = mDataService.getGood(mMenu.goodId ?: 0)
        if (good != null) {
            if (menu.logoId == null) menu.logoId = good?.logoId
            if (menu.name == null) menu.name = good?.name

            var array = good.remark?.split(";")
            var color = if (array != null && array.size >= 2) array[1] else "#FFFFFF"
            backgroundColor.value = Color.parseColor(color)
        }
        name.value = mMenu.name
        val image = mDataService.getImage(menu.logoId)
        uri.value = "file://${mDataService.imagesPath}/${image?.fileName}"

        uriRemark.value = "res://${mApp.packageName}/${R.mipmap.remark}"
        hasRemark.value = (mMenu.group == 2)
        price.value = (mMenu.price / 100.0).toString()
        proRemark.value = mMenu.remark?:""
        uriSeal.value = "res://${mApp.packageName}/${R.mipmap.seal1}"
        btnSeal1.value = mApp.getDrawable(R.mipmap.btn_seal11)
        btnSeal2.value = mApp.getDrawable(R.mipmap.btn_seal22)
        sealIndex = 0

        uriSugar.value = "res://${mApp.packageName}/${R.mipmap.sugar2}"
        btnSugar1.value = mApp.getDrawable(R.mipmap.btn_sugar12)
        btnSugar2.value = mApp.getDrawable(R.mipmap.btn_sugar21)
        btnSugar3.value = mApp.getDrawable(R.mipmap.btn_sugar32)
        sugarIndex = 0
        this.downCount.value = 60
    }

    fun onClickSeal1() {
        uriSeal.value = "res://${mApp.packageName}/${R.mipmap.seal1}"
        btnSeal1.value = mApp.getDrawable(R.mipmap.btn_seal11)
        btnSeal2.value = mApp.getDrawable(R.mipmap.btn_seal22)
        sealIndex = 1
    }

    fun onClickSeal2() {
        uriSeal.value = "res://${mApp.packageName}/${R.mipmap.seal2}"
        btnSeal1.value = mApp.getDrawable(R.mipmap.btn_seal12)
        btnSeal2.value = mApp.getDrawable(R.mipmap.btn_seal21)
        sealIndex = 2
    }

    fun onClickSugar1() {
        uriSugar.value = "res://${mApp.packageName}/${R.mipmap.sugar1}"
        btnSugar1.value = mApp.getDrawable(R.mipmap.btn_sugar11)
        btnSugar2.value = mApp.getDrawable(R.mipmap.btn_sugar22)
        btnSugar3.value = mApp.getDrawable(R.mipmap.btn_sugar32)
        sugarIndex = 1
    }

    fun onClickSugar2() {
        uriSugar.value = "res://${mApp.packageName}/${R.mipmap.sugar2}"
        btnSugar1.value = mApp.getDrawable(R.mipmap.btn_sugar12)
        btnSugar2.value = mApp.getDrawable(R.mipmap.btn_sugar21)
        btnSugar3.value = mApp.getDrawable(R.mipmap.btn_sugar32)
        sugarIndex = 2
    }

    fun onClickSugar3() {
        uriSugar.value = "res://${mApp.packageName}/${R.mipmap.sugar3}"
        btnSugar1.value = mApp.getDrawable(R.mipmap.btn_sugar12)
        btnSugar2.value = mApp.getDrawable(R.mipmap.btn_sugar22)
        btnSugar3.value = mApp.getDrawable(R.mipmap.btn_sugar31)
        sugarIndex = 3
    }

    fun onClickScanQr() {
        var order = this.addProduct(sealIndex,sugarIndex)
        stopCheckDeployTimer()
        var bundle = Bundle()
        bundle.putString("UI", "ScanQr")
        bundle.putLong("OrderId", order.id)
        bundle.putLong("goodId", goodId)
        bundle.putInt("sealIndex", sealIndex)
        bundle.putInt("sugarIndex", sugarIndex)
        LiveEventBus.get("SwitchUI").post(bundle)
    }

    fun onClickCancel() {
        //mDataService.insertLog("OrderDVM:"+ mDataService.currentOrder?.id.toString())
        mDataService.currentOrder = null
        mDeviceService.isMakingProduct = false
        var bundle = Bundle()
        bundle.putString("UI", "Menus")
        LiveEventBus.get("SwitchUI").post(bundle)
    }

    fun addProduct(sealIndex:Int,sugarIndex:Int): Order {
        if (this.order == null) this.order = Order()
        var order = this.order!!
        if (order.id <= 0) {
            order.createTime = Date(System.currentTimeMillis())
            order.timestamp = order.createTime
            val sdFormatter = SimpleDateFormat("yyMMddHHmmssSSS")
            sdFormatter.setTimeZone(TimeZone.getTimeZone("GMT+8"))
            val time = sdFormatter.format(order.createTime)
            order.id = java.lang.Long.parseLong(time) / 1000 * 10000000 + mDataService.terminalId * 10
        }
        if (this.orderDetail == null) {
            this.orderDetail = OrderDetail()
            order.details.add(this.orderDetail);
        }
        var detail = this.orderDetail!!
        detail.no = order.details.size
        detail.goodId = mMenu.goodId
        detail.memuNo = mMenu.no
        detail.name = mMenu.name
        detail.count = 1
        detail.price = mMenu.price
        detail.realAmount = detail.count * detail.price
        detail.remark = this.getReceipes()
        mDataService.save(order)
        mDataService.currentOrder = this.order
        mDataService.insertLog("Order:生成订单号:"+mDataService.currentOrder?.id.toString())
        return this.order!!
    }

    fun getReceipes(): String {
        var result = "10002:"
        when (sealIndex) {
            0 -> result += "0"//1默认有盖   0无盖
            1 -> result += "0"
            2 -> result += "1"
        }
        result += ";"

        result += "11004:"
        var receipes = mDataService.getReceipes(mMenu.goodId)
        var receipe = receipes.find { x -> x.ingridentId == 11004 }
        if (receipe != null) {
            when (sugarIndex) {
                0 -> result += receipe.std
                1 -> result += receipe.min
                2 -> result += receipe.std
                3 -> result += receipe.max
            }
        } else {
            when (sugarIndex) {
                0 -> result += "70"
                1 -> result += "20"
                2 -> result += "70"
                3 -> result += "100"
            }
        }
        result += ";"
        return result
    }

    fun stopCheckDeployTimer(){
        this.mCheckTimer?.cancel()
        this.mCheckTimer = null
    }

    fun startCheckDeployTimer() {
        this.downCount.postValue(60)
        this.mCheckTimer = Timer()
        this.mCheckTimer?.schedule(1000, 1000, {
            var count = Math.max(0, (downCount.value ?: 1) - 1)
            downCount.postValue(count)
            if (count <= 0){
                stopCheckDeployTimer()
                mDeviceService.isMakingProduct = false
                //mDataService.insertLog("DVM2")
                uiNotify.postValue(getNotify("Timeout"))
            }
        })
    }
}